Page({
  data: {
    deviceId: '',
    serviceId: '6E400001-B5A3-F393-E0A9-E50E24DCCA9E',
    readCharacteristicId: '6E400003-B5A3-F393-E0A9-E50E24DCCA9E',
    writeCharacteristicId: '6E400002-B5A3-F393-E0A9-E50E24DCCA9E',
    receiveMessage: '',
    sendMessage: '',
    logMessage: '',
    historyData: [], // 历史数据数组
    lastRenderTime: 0,  // 最后渲染时间戳
    staticDrawnFlag: false // 新增静态绘制标记
  },
  onLoad: function (options) {
    this.staticDrawnFlag = false; // 新增初始化
    this.setData({
      deviceId: options.deviceId
    });
    this.connectToDevice();
  },
  connectToDevice: function () {
    wx.createBLEConnection({
      deviceId: this.data.deviceId,
      success: (res) => {
        console.log('连接成功', res);
        this.getDeviceServices(); 
      },
      fail: (res) => {
        console.log('连接失败', res);
      }
    });
  },
  getDeviceServices: function () {
    wx.getBLEDeviceServices({
      deviceId: this.data.deviceId,
      success: (res) => {
        const serviceCount = res.services.length;
        const serviceUuids = res.services.map(service => service.uuid).join(', ');
        console.log(`获取服务成功，共搜索到 ${serviceCount} 个服务，UUID 分别为：${serviceUuids}`);
        this.getDeviceCharacteristics();
      },
      fail: (res) => {
        console.log('获取服务失败', res);
      }
    });
  },
  getDeviceCharacteristics: function () {
    wx.getBLEDeviceCharacteristics({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      success: (res) => {
        console.log('获取特征值成功', res.characteristics);
        this.notifyBLECharacteristicValueChange(); 
      },
      fail: (res) => {
        console.log('获取特征值失败', res);
      }
    });
  },
  notifyBLECharacteristicValueChange: function () {
    wx.notifyBLECharacteristicValueChange({
      state: true,
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.readCharacteristicId,
      success: (res) => {
        console.log('启用通知成功', res);
        wx.onBLECharacteristicValueChange((res) => {
          const value = this.ab2hex(res.value);
          const byteCount = res.value.byteLength;
          const uint8Array = new Uint8Array(res.value);
  
          const intValue = (uint8Array[3] << 24) | (uint8Array[4] << 16) | (uint8Array[5] << 8) | uint8Array[6];
          // 更新历史数据数组
          const newHistory = [...this.data.historyData, intValue].slice(-200);
            // 优化点2：分离数据更新与界面更新
          this.setData({
            logMessage: `收到${byteCount}字节: ${value}\n`,
            receiveMessage: value,
            historyData: newHistory
          }, () => {
            // 优化点3：限制绘制频率（每秒最多30帧）
            const now = Date.now();
            if (now - this.data.lastRenderTime > 33) { // 约30fps
              this.drawHistoryCurve();
              this.setData({ lastRenderTime: now });
            }
          });
        });
      },
      fail: (res) => {
        console.log('启用通知失败', res);
      }
    });
  },
  sendMessage: function () {
    const buffer = this.str2ab(this.data.sendMessage);
    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.writeCharacteristicId,
      value: buffer,
      success: (res) => {
        console.log('发送消息成功', res);
      },
      fail: (res) => {
        console.log('发送消息失败', res);
      }
    });
  },
  ab2hex: function (buffer) {
    const byteArray = new Uint8Array(buffer);
    let hexString = '';
    for (let i = 0; i < byteArray.length; i++) {
      const hex = byteArray[i].toString(16).padStart(2, '0');
      hexString += hex;
    }
    return hexString;
  },
  ab2str: function (buf) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
  },
  str2ab: function (str) {
    const buf = new ArrayBuffer(str.length);
    const bufView = new Uint8Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  },
  onInputChange: function (e) {
    this.setData({
      sendMessage: e.detail.value
    });
  },
// 优化后的绘制函数
drawHistoryCurve: function () {
  const ctx = wx.createCanvasContext('historyCurve');
  const { historyData } = this.data;
  
  // 移除离屏canvas相关代码
  this.drawStaticElements(ctx); // 直接绘制到主canvas
  
  // 动态曲线绘制优化
  ctx.beginPath();
  const minVal = Math.min(...historyData);
  const maxVal = Math.max(...historyData);
  const range = maxVal - minVal || 1;
  
  historyData.forEach((value, i) => {
    const x = (i / historyData.length) * 350;
    const y = 200 - ((value - minVal) / range) * 200;
    i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
  });
  
  ctx.strokeStyle = '#FF0000';
  ctx.stroke();
  ctx.draw(); // 必须调用draw才能生效
},

// 修复静态元素初始化
drawStaticElements: function(ctx) {
  if (!this.staticDrawnFlag) { // 使用实例变量代替data中的状态
    ctx.beginPath();
    ctx.moveTo(0, 200);
    ctx.lineTo(350, 200);
    ctx.strokeStyle = '#000';
    ctx.stroke();
    this.staticDrawnFlag = true; // 初始化实例变量
  }
},

});
